package com.laikan.reader.bookfriend.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import com.baidu.api.Baidu;
import com.baidu.api.BaiduDialog;
import com.baidu.api.BaiduDialogError;
import com.baidu.api.BaiduException;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.helpers.BasicEvent;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.DeviceUtil;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.apirequester.BookShelfRequester;
import com.laikan.reader.apirequester.LoginRequester;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.LaikanApplication;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.QQUserInfoBean;
import com.laikan.reader.core.bean.WBUserInfoBean;
import com.laikan.reader.core.bean.WXUserInfoBean;
import com.laikan.reader.core.events.LaiKanEvent;
import com.laikan.reader.core.utils.AccountManager;
import com.laikan.reader.core.utils.ActivityUitl;
import com.laikan.reader.core.utils.CountDownTimerUtils;
import com.laikan.reader.core.utils.PublicUtil;
import com.laikan.reader.database.Book;
import com.laikan.reader.database.db.DAO;
import com.mob.tools.utils.UIHandler;
import com.socks.library.KLog;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;

import static com.laikan.reader.bookstart.activity.GuideActivity.isWeixinAvilible;

/**
 * 登录页
 *
 * @author wx
 */
public class LoginActivity extends BasicActivity implements View.OnClickListener, Handler.Callback {

    /**
     * 百度登录数据
     */
    private final static String Scope_Basic = "basic";
    private final static String Scope_Netdisk = "netdisk";
    private static final int MSG_USERID_FOUND = 1;
    private static final int MSG_LOGIN = 2;
    private static final int MSG_AUTH_CANCEL = 3;
    private static final int MSG_AUTH_ERROR = 4;
    private static final int MSG_AUTH_COMPLETE = 5;
    private Button login_btn;
    private ImageView login_weixin;
    /**
     * 标题栏
     */
    Drawable drawable_back_tv;
    // private TextView register;
    private TextView register;
    private TextView findpsw;
    private ImageView qqlogin, xllogin, baidulogin, back_tv;
    private EditText name, password;
    private String mPassword;
    private TelephonyManager tm;
    /**
     * 登出操作对应的listener
     */
    private String thirdtype = "1";
    // 书架缓存列表
    private ArrayList<Book> cacheBookList;
    // private File File = null;
    private int reqLogin = 1;
    private DAO dao;

    private final SendAuth.Req req = new SendAuth.Req();
    private LocalBroadcastManager localBroadcastManager;
    private LocalReceiver localReceiver;
    private RelativeLayout back_layout;
    private TextView mButton;
    private boolean isChapterRefer = false;
    private Baidu baidu = null;
    private CountDownTimerUtils mCountDownTimerUtils;

    public void setView(BaseDataBean result) {
        LaikanApplication.mess = result.getMessageVersion();
        if (!TextUtils.isEmpty(result.getAppStart())) {
            ToastMgr.showShortToast(result.getAppStart());
        }
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        System.out.println(SPUtil.getString("psdString", "") + "-=-=-");
        if (!SPUtil.getString("psdString", "").equals("")) {
            String[] psd = SPUtil.getString("psdString", "").split("/");
            SPUtil.putString("psdString", "");
            name.setText(psd[1]);
            password.setText(psd[0]);
            UserLogin();
        }
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void assignViews() {
        setContentView(R.layout.lk_login_new);
        Constants.api = WXAPIFactory.createWXAPI(getApplicationContext(), Constants.WX_APP_ID, false);
        Constants.api.registerApp(Constants.WX_APP_ID);
        ShareSDK.initSDK(this);
        localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.laikan.broadcast.LOGIN");
        localReceiver = new LocalReceiver();
        localBroadcastManager.registerReceiver(localReceiver, intentFilter);
        baidulogin = (ImageView)findViewById(R.id.baidulogin);
        xllogin = (ImageView)findViewById(R.id.xllogin);
        qqlogin = (ImageView)findViewById(R.id.qqlogin);
        name = (EditText)findViewById(R.id.et_phone);
        password = (EditText)findViewById(R.id.et_password);
        login_btn = (Button)findViewById(R.id.btn_login);
        login_weixin = (ImageView)findViewById(R.id.login_weixin);
        back_tv = (ImageView)findViewById(R.id.iv_back);
        back_layout = (RelativeLayout)findViewById(R.id.back_layout);
        mButton = (TextView)findViewById(R.id.tv_yanzheng);
    }

    @SuppressWarnings ("static-access")
    @Override
    protected void initData() {
        openEventBus();
        dao = new DAO(mContext);
        isChapterRefer = getIntent().getBooleanExtra("isChapterRefer", false);
        tm = (TelephonyManager)getSystemService(mContext.TELEPHONY_SERVICE);
        drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
        back_tv.setImageDrawable(drawable_back_tv);
    }

    @Override
    protected void setListener() {
        baidulogin.setOnClickListener(this);
        xllogin.setOnClickListener(this);
        qqlogin.setOnClickListener(this);
        login_btn.setOnClickListener(this);
        login_weixin.setOnClickListener(this);
        back_layout.setOnClickListener(this);
        mButton.setOnClickListener(this);
        name.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    InputMethodManager imm = ((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE));
                    imm.hideSoftInputFromWindow(name.getWindowToken(), 0);
                }
            }
        });
        password.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    InputMethodManager imm = ((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE));
                    imm.hideSoftInputFromWindow(password.getWindowToken(), 0);
                }
            }
        });
    }

    @Override
    protected void parseEvent(BasicEvent event) {

        switch (event.getEventID()){
            case LaiKanEvent.EVENT_ID_FINISH_LOGIN:
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_yanzheng:
                if (DeviceUtil.isMobileNO(name.getText().toString().trim())) {
                    mCountDownTimerUtils = new CountDownTimerUtils(mButton, 60000, 1000);
//                    mCountDownTimerUtils.start();
                    getYanZhengMa();
                }else {
                    ToastMgr.showShortToast(R.string.login_phone_number_invalid);
                }
                break;
            case R.id.back_layout:            //返回键
                name.clearFocus();
                password.clearFocus();
                finish();
                break;
            case R.id.btn_login:        // 普通登录
                MobclickAgent.onEvent(mContext, "lk_login_new");
                mPassword = password.getText().toString().trim();
                if (DeviceUtil.isMobileNO(name.getText().toString().trim())) {
                    if (mPassword.equals("")) {
                        ToastMgr.showShortToast(R.string.login_yanzheng_is_not_empty);
                    }else {
                        UserLogin();
                    }
                }else {
                    ToastMgr.showShortToast(R.string.login_phone_number_invalid);
                }
                break;

            case R.id.login_weixin:     // 微信登录
                MobclickAgent.onEvent(this, "weixin_login");
                if(ActivityUitl.isNetworkAvailable(mContext)){
                    if (isWeixinAvilible(this)) {
                        thirdtype = "6";
                        // authorize(new Wechat(this));
                        req.scope = "snsapi_userinfo";
                        req.state = "wechat_sdk_demo_test";
                        Constants.api.sendReq(req);
                        KLog.e("249 微信登录...");
                    }else {
                        Toast.makeText(this, R.string.login_weixin_not_installed, Toast.LENGTH_SHORT).show();
                    }
                }else{
                    ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                }
                break;

            case R.id.xllogin:          // 新浪微博登录
                MobclickAgent.onEvent(mContext, "sina_login");
                if(ActivityUitl.isNetworkAvailable(mContext)){
                    thirdtype = "1";
                    Platform weibo = ShareSDK.getPlatform(this, SinaWeibo.NAME);
                    authorize(weibo);
                }else{
                    ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                }
                break;

            case R.id.baidulogin:       // 百度登录
                MobclickAgent.onEvent(mContext, "baidu_login");
                thirdtype = "5";
                startBaidu();
                break;

            case R.id.qqlogin:          // QQ登录
                MobclickAgent.onEvent(mContext, "qq_login");
                if(ActivityUitl.isNetworkAvailable(mContext)){
                    thirdtype = "4";
                    Platform qqPlatform = ShareSDK.getPlatform(this, QQ.NAME);
                    authorize(qqPlatform);
                }else{
                    ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                }
                break;
            default:
                break;
        }
    }

    private void getYanZhengMa() {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("mobile", name.getText().toString().trim());  //手机号
        map.put("deviceId", tm.getDeviceId()); //设备号
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                if (httpResponse == null || httpResponse.responseContent == null) {
                    return;
                }
                BaseDataBean result;
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean>() {
                }.getType();
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);
                    if (result != null) {
                        if (result.getError_no().equals("704")) {
//                            mCountDownTimerUtils = new CountDownTimerUtils(mButton, 60000, 1000);
                            mCountDownTimerUtils.start();
                            ToastMgr.showShortToast(R.string.login_yanzheng_send);
                        } else {
                            mCountDownTimerUtils.onFinish();
                            ToastMgr.showShortToast(result.getError_msg());
                        }
                    }
                }catch (Exception e) {
                    mCountDownTimerUtils.onFinish();
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    e.printStackTrace();
                }finally {
                }

            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                mCountDownTimerUtils.onFinish();
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.getRootURL() + "accounts/logincode");
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.getRootURL() + "accounts/logincode", map, null, null, requestListener);
    }

    /**
     * 第三方登录接口 当第三方sdk 回调成功后 调用此接口
     */
    private void thirdLogin() {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("type", thirdtype);
        map.put("thirdId", SPUtil.getString("openid", ""));
        map.put("name", SPUtil.getString("dsf_name", ""));
        map.put("deviceId", tm.getDeviceId());
        map.put("ua", android.os.Build.MODEL);
        if ("6".equals(thirdtype)) {
            map.put("unionId", SPUtil.getString("unionid", ""));
        }

        // 115.28.36.155:8080 现网
        // 10.1.16.229:8080
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                if (httpResponse == null || httpResponse.responseContent == null) {
                    return;
                }
                try {
                    JSONObject obj = new JSONObject(httpResponse.responseContent);
                    //                    KLog.e("299 thirdLogin() json = " + json);
                    String result = obj.getString("result");
                    if (Constants.RESULT_OK.equals(result)) {
                        JSONObject data = obj.getJSONObject("data");
                        if(AccountManager.getInstance().isSwitchAccount(data.getString("token"))){
                            if(!TextUtils.isEmpty(SPUtil.getString("token", ""))){
                                AccountManager.getInstance().clearAccountData();
                            }
                        }
                        SPUtil.putString("token", data.getString("token"));
                        SPUtil.putString("user_id", data.getString("id"));
                        SPUtil.putString("user_name", data.getString("name"));
                        SPUtil.putString("user_score", data.getString("score"));
                        SPUtil.putString("user_level", data.getString("level"));
                        SPUtil.putString("user_icon", data.getString("icon"));
                        ToastMgr.showShortToast(R.string.login_success);
                        SPUtil.putBoolean("switch_account", true);
                        SPUtil.putBoolean("login_laikan_setting", true);
                        BookShelfRequester.syncBookFromServer();
                        dao.distributionTask();
                        // 同步本地书架列表
                        SPUtil.putBoolean("isGetAssetsGift", false);
                    }else {
                        ToastMgr.showShortToast(obj.getString("error_msg"));
                    }
                }catch (JSONException e) {
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    e.printStackTrace();
                }finally {
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                KLog.e("网络不给力，请重试。22");

            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.getRootURL() + "accounts/thirdUserLogin");
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.getRootURL() + "accounts/thirdUserLogin", map, null, null, requestListener);
    }

    private void UserLogin() {
        mPassword = password.getText().toString().trim();
        HashMap<String, String> map = new HashMap<>();
        map.put("mobile", name.getText().toString().trim());
        map.put("code", mPassword);
        map.put("deviceId", tm.getDeviceId());
        map.put("ua", android.os.Build.MODEL);
        if ("6".equals(thirdtype)) {
            map.put("unionId", SPUtil.getString("unionid", ""));
        }
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                try {
                    JSONObject obj = new JSONObject(httpResponse.responseContent);
                    KLog.i("", obj.toString());
                    int result_code = obj.optInt("result");
                    if (Constants.RESULT_OK.equals(result_code + "")) {
                        JSONObject data = obj.getJSONObject("data");
                        if(AccountManager.getInstance().isSwitchAccount(data.getString("token"))){
                            if(!TextUtils.isEmpty(SPUtil.getString("token", ""))){
                                AccountManager.getInstance().clearAccountData();
                            }
                        }
                        SPUtil.putString("token", data.getString("token"));
                        SPUtil.putString("user_id", data.getString("id"));
                        SPUtil.putString("user_name", data.getString("name"));
                        SPUtil.putString("user_score", data.getString("score"));
                        SPUtil.putString("user_level", data.getString("level"));
                        SPUtil.putString("user_icon", data.getString("icon"));
                        ToastMgr.showShortToast(R.string.login_success);
                        MobclickAgent.onEvent(mContext,"mobile_num_login");
                        MobclickAgent.onEvent(mContext,"laikan_login_count");
                        //(LoginActivity是当前的Activity)
                        ((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(LoginActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                        SPUtil.putBoolean("switch_account", true);
                        SPUtil.putBoolean("login_laikan_setting", true);
                        BookShelfRequester.syncBookFromServer();
                        dao.distributionTask();
                        // 同步本地书架列表
                        SPUtil.putBoolean("isGetAssetsGift", false);
                        finish();
                    }else {
                        ToastMgr.showShortToast(obj.getString("error_msg"));
                    }

                }catch (JSONException e) {
                    e.printStackTrace();
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                }finally {
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                reqLogin++;
                if (reqLogin <= 3) {
                    UserLogin();
                }
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_login);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.laikan_login, map, null, null, requestListener);
    }

    /**
     * 启动 百度登录
     */
    protected void startBaidu() {

        baidu = new Baidu(Constants.APIKEY, this);
        if (baidu.isSessionValid()) { //避免在Session期内，自动登录
            baidu.clearAccessToken();
            baidu = null;
        }
        baidu = new Baidu(Constants.APIKEY, this);

        baidu.authorize(this, false, true, new BaiduDialog.BaiduDialogListener() {
            @Override
            public void onComplete(Bundle bundle) {
                LoginRequester.baiduLogin(tm, baidu, dao);
            }

            @Override
            public void onBaiduException(BaiduException e) {
                ToastMgr.showShortToast(R.string.login_baidu_failed);
            }

            @Override
            public void onError(BaiduDialogError baiduDialogError) {
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
            }

            @Override
            public void onCancel() {
                ToastMgr.showShortToast(R.string.login_cancel);
            }
        });
    }

    //---------------使用share sdk集成第三方登录 start---------------------------

    private void authorize(Platform plat) {
        // 已授权
        plat.removeAccount();
        if (plat.isValid()) {    // 判断指定平台是否已经完成授权
            String userId = plat.getDb().getUserId();
            if (!TextUtils.isEmpty(userId)) {
                parseThirdUserInfo(plat);
                UIHandler.sendEmptyMessage(MSG_USERID_FOUND, this);
                return;
            }
        }

        // 未授权
        plat.setPlatformActionListener(new ShareSDKPlatformActionListener());
        plat.SSOSetting(false);    // true不使用SSO授权，false使用SSO授权
        plat.showUser(null);    // 要数据，不要功能
        // plat.authorize();	// 要功能，不要数据（用户）
    }

    /**
     * 获取用户信息进行登录
     *
     * @param plat
     */
    private void parseThirdUserInfo(Platform plat) {
        String exportData = plat.getDb().exportData();
        Gson gson = new Gson();
        Type type = null;
        String platName = plat.getName();
        if (platName.equals(Wechat.NAME)) {
            // 获取微信用户信息
            WXUserInfoBean userInfo = new WXUserInfoBean();
            type = new TypeToken<WXUserInfoBean>() {}.getType();
            userInfo = gson.fromJson(exportData, type);
            SPUtil.putString("openid", userInfo.getOpenid());
            SPUtil.putString("dsf_name", userInfo.getNickname());
            SPUtil.putString("unionid", userInfo.getUnionid());

        }else if (platName.equals(QQ.NAME)) {
            // 获取QQ用户信息
            QQUserInfoBean userInfo = new QQUserInfoBean();
            type = new TypeToken<QQUserInfoBean>() {
            }.getType();
            userInfo = gson.fromJson(exportData, type);
            SPUtil.putString("openid", userInfo.getUserID());
            SPUtil.putString("dsf_name", userInfo.getNickname());
            LoginRequester.qqLogin(tm, userInfo, dao);

        }else if (platName.equals(SinaWeibo.NAME)) {
            // 获取新浪微博用户信息
            WBUserInfoBean userInfo = new WBUserInfoBean();
            type = new TypeToken<WBUserInfoBean>() {
            }.getType();
            userInfo = gson.fromJson(exportData, type);
            SPUtil.putString("openid", userInfo.getUserID());
            SPUtil.putString("dsf_name", userInfo.getNickname());
            LoginRequester.weiboLogin(tm, userInfo, dao);
        }

        KLog.e("970 plat.getDb().exportData() = " + exportData);
        //  UIHandler.sendEmptyMessage(MSG_LOGIN, this);
    }

    private class ShareSDKPlatformActionListener implements PlatformActionListener {

        /**
         * 获取授权成功回调
         */
        @Override
        public void onComplete(Platform platform, int action, HashMap<String, Object> res) {
            if (action == Platform.ACTION_USER_INFOR) {    // 获取用户信息
                parseThirdUserInfo(platform);
                UIHandler.sendEmptyMessage(MSG_AUTH_COMPLETE, LoginActivity.this);
            }
        }

        /**
         * 登录失败
         */
        @Override
        public void onError(Platform platform, int action, Throwable t) {
            if (action == Platform.ACTION_USER_INFOR) {
                Message msg = new Message();
                msg.what = MSG_AUTH_ERROR;
                msg.obj = platform.getName();
                UIHandler.sendMessage(msg, LoginActivity.this);
            }
            t.printStackTrace();
        }

        /**
         * 取消登录
         */
        @Override
        public void onCancel(Platform platform, int action) {
            if (action == Platform.ACTION_USER_INFOR) {
                UIHandler.sendEmptyMessage(MSG_AUTH_CANCEL, LoginActivity.this);
            }
        }
    }

    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_LOGIN: {
                // 登录
                thirdLogin();
            }
            break;
            case MSG_AUTH_CANCEL: {    // 取消登录
                Toast.makeText(this, R.string.auth_cancel, Toast.LENGTH_SHORT).show();
            }
            break;
            case MSG_AUTH_ERROR: {    // 登录失败
//                Toast.makeText(this, R.string.auth_error, Toast.LENGTH_SHORT).show();
                Toast.makeText(this, R.string.laikan_network_anomaly, Toast.LENGTH_SHORT).show();
                // 平台名称
                String platName = (String)msg.obj;
                Platform plat = null;
                if (platName.equals(Wechat.NAME)) {
                    // 微信
                    plat = ShareSDK.getPlatform(this, Wechat.NAME);
                }else if (platName.equals(QQ.NAME)) {
                    // QQ
                    plat = ShareSDK.getPlatform(this, QQ.NAME);
                }else if (platName.equals(SinaWeibo.NAME)) {
                    // 新浪微博
                    plat = ShareSDK.getPlatform(this, SinaWeibo.NAME);
                }
                if (plat != null) {
                    // 删除授权
                    plat.removeAccount(true);
                }
            }
            break;
            case MSG_AUTH_COMPLETE: {    // 授权成功的回调
                // 授权成功，正在跳转登录操作…
                Toast.makeText(this, R.string.auth_complete, Toast.LENGTH_SHORT).show();
            }
            break;
        }
        return false;
    }
    //---------------使用share sdk集成第三方登录 end---------------------------

    /**
     * 微信登录广播
     */
    class LocalReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String code = intent.getStringExtra("code");
            LoginRequester.weixinLogin(tm,code,dao);
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        localBroadcastManager.unregisterReceiver(localReceiver);
    }
}
